package me.sealer.ssm.controller;

import lombok.extern.slf4j.Slf4j;
import me.sealer.ssm.constant.Dict;
import me.sealer.ssm.constant.PermissionConstant;
import me.sealer.ssm.constant.ShortUrlConstant;
import me.sealer.ssm.model.ShortUrl;
import me.sealer.ssm.service.ShortUrlService;
import me.sealer.ssm.utils.UrlUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author sealer
 * @date 2017/06/19
 */
@Slf4j
@Controller
@RequestMapping("/urlOperations")
@RequiresPermissions(value = {PermissionConstant.URL_MGMT})
public class ShortUrlController {
    private final ShortUrlService shortUrlService;

    public ShortUrlController(ShortUrlService shortUrlService) {
        this.shortUrlService = shortUrlService;
    }

    @RequestMapping("/preGenShortUrl")
    public String preGenShortUrl() {
        return "genShortUrl";
    }

    @RequestMapping(value = "/genShortUrl", method = RequestMethod.POST)
    public ModelAndView generateShortUrl(HttpServletRequest request) {
        String longUrlReq = request.getParameter(Dict.LONG_URL);

        //如果长地址不是以http开头， 则添加默认协议 http:// 注意：https亦是http开头。
        if (!longUrlReq.startsWith(ShortUrlConstant.HTTP)) {
            longUrlReq = "http://" + longUrlReq;
        }

        ShortUrl shortUrl = new ShortUrl();
        shortUrl.setLongUrl(longUrlReq);

        //将长URL插入数据库
        shortUrlService.insertOne(shortUrl);

        //拿到刚插入的记录的ID， 用作生成短URL
        shortUrl = shortUrlService.selectByLongUrl(longUrlReq);
        int id = shortUrl.getId();

        //生成短URL
        String sUrl = UrlUtil.getShortUrl(id, 6);

        //将生成的短URL更新到数据库
        shortUrl.setShortUrl(sUrl);
        shortUrlService.updateByLongUrl(shortUrl);

        //将短地址反显给用户
        ModelAndView mav = new ModelAndView();
        mav.addObject(Dict.SHORT_URL, "http://sealer.me/short/" + sUrl);
        mav.setViewName("shortUrlResult");

        return mav;
    }
}
